import DGDialogLayout from "../../../components/DGDialogLayout/DGDialogLayout.tsx";
import DGTextView from "../../../components/DGTextView.tsx";
import DGDrawerLayout from "../../../components/DGDrawerLayout/DGDrawerLayout.tsx";
import {useNavigate} from "react-router-dom";
import {Box, FormControl, FormHelperText, Input, InputAdornment, InputLabel, TextField} from "@mui/material";
import {ChangeEventHandler, FC, useEffect, useState} from "react";
import AppProvider from "../../../sources/AppProvider.ts";
import DGToast from "../../../components/DGToast.tsx";
import {AlertColor} from "@mui/material/Alert/Alert";
import IconButton from "@mui/material/IconButton";
import {Visibility, VisibilityOff} from "@mui/icons-material";
import DGConnect from "../../../sources/DGConnect.ts";
import {Util} from "../../../sources/Util.ts";

interface ChangeAccountProps {
    state: boolean;
    close: () => void;
}

interface DGToastProps {
    state: boolean,
    severity: AlertColor,
    text: string
}

const ChangeAccount: FC<ChangeAccountProps> = ({state, close}) => {
    // 全局上下文
    const App = AppProvider.useAppContext();
    // 路由跳转
    const router = useNavigate();
    // Toast 弹窗
    const [toast, setToast] = useState<DGToastProps>({state: false, severity: "info", text: ""});
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 账号信息
    const [account, setAccount] = useState("");
    // 账号错误信息
    const [AccountError, setAccountError] = useState({state: false, text: ""});
    // 密码显示控制
    const [showPwd, setShowPwd] = useState(false);
    // 密码信息
    const [password, setPassword] = useState("");
    // 密码错误信息
    const [PasswordError, setPasswordError] = useState({state: false, text: ""});


    // 账号验证信息
    const setAccountVerify = (text: string) => {
        if (text.indexOf(' ') > -1) return {state: true, text: "不允许存在空格！"};
        if (text.length < 4) return {state: true, text: "不能小于 4 位！"};
        if (text.length > 30) return {state: true, text: "不能大于 30 位！"};
        if (!/^[a-zA-Z0-9_]{4,30}$/.test(text)) return {state: true, text: "逐梦园账号格式错误，请确保输入正确！"};
        return {state: false, text: ""};
    }


    // 更改账号操作
    const handleChangeAccount: ChangeEventHandler<HTMLInputElement> = e => {
        // 清除账号错误信息
        setAccountError({state: false, text: ""});
        // 清除密码错误信息
        setPasswordError({state: false, text: ""});
        // 设置账号信息
        setAccount(e.target.value);
        // 验证账号是否存在错误
        const error = setAccountVerify(e.target.value);
        if (error.state) setAccountError({state: error.state, text: error.text});
    }


    // 更改密码操作
    const handleChangePassword: ChangeEventHandler<HTMLInputElement> = e => {
        // 清除账号错误信息
        setAccountError({state: false, text: ""});
        // 清除密码错误信息
        setPasswordError({state: false, text: ""});
        // 设置密码信息
        setPassword(e.target.value);
    }


    // 提交函数
    const handleSubmit = () => {
        // 清除账号错误信息
        setAccountError({state: false, text: ""});
        // 清除密码错误信息
        setPasswordError({state: false, text: ""});
        // 判断账号是否为空
        if (account === "") return setAccountError({state: true, text: "账号输入不能为空！"});
        // 判断账号是否未修改
        if (App && App!.info && App!.info['account'] === account) return setAccountError({
            state: true, text: "账号没有任何修改！"
        });
        // 验证账号是否存在错误
        const error = setAccountVerify(account);
        if (error.state) return setAccountError({state: error.state, text: error.text});
        // 开始加载
        setLoading(true);
        // 发起请求验证
        DGConnect.POST(JSON.stringify({
                info: "changeAccount", account: account, password: password
            }), result => {
                // 关闭加载
                setLoading(false);
                // 判断错误信息
                if (result['data']['code'] !== 200) {
                    // 判断是账号错误信息
                    if ([201, 202, 203, 204, 205, 206, 209, 213].includes(result['data']['code'])) return setAccountError({
                        state: true, text: result['data']['message'] + "错误码：" + result["data"]["code"]
                    });
                    return setPasswordError({
                        state: true, text: result['data']['message'] + "错误码：" + result["data"]["code"]
                    });
                }
                // 获取本地信息
                const userInfo = Util.Storage.getLocal("LOGIN-USER")
                // 验证是否邮箱
                if (!App!.Regex['email'].test(userInfo['username'])) {
                    // 将登陆账户和密码存储在本地
                    Util.Storage.setLocal("LOGIN-USER", {username: account, password: userInfo['password']});
                }
                // 更新会话信息
                App!.setUserInfo(result['data']['result']);
                // 提示修改完成
                setToast({state: true, severity: "success", text: result['data']['message']});
                // 关闭弹窗
                setTimeout(() => handleClose(1), 500);
            }, error => {
                // 关闭加载
                setLoading(false);
                // 提示更改失败
                setPasswordError({
                    state: true, text: "遇到了一些问题，请尝试重试，或者及时联系我们！错误信息：" + error['stack']
                });
            }
        )
        ;
    }


    // 关闭控制
    const handleClose = (id: number) => {
        // 关闭
        close();
        // 后退
        if (id === 1) router(-1);
    }

    useEffect(() => {
        // 设置默认账号信息
        if (App && App!.info) setAccount(String(App!.info['account']));
        // 清空密码信息
        setPassword("");
        // 清除账号错误信息
        setAccountError({state: false, text: ""});
        // 清除密码错误信息
        setPasswordError({state: false, text: ""});
    }, [App, App?.info, state]);


    const ContentView = (<>
        {/* 未登录提示语 */}
        {!App!.info && <DGTextView Body Bold>您当前未登陆账户，服务不可用！</DGTextView>}

        {/* 已登录 */}
        {App!.info && <Box style={{display: "flex", flexDirection: "column", gap: "10px"}}>

            {/* 显示上次修改时间 */}
            {Boolean(App!.info["cas"]) && <DGTextView Body Bold>
                当前账号：{String(App!.info["account"])}
            </DGTextView>}

            {/* 显示上次修改时间 */}
            {Boolean(App!.info["cas"]) && <DGTextView Body Bold>
                上次修改：{String(App!.info["cat"] || "无")}
            </DGTextView>}

            <DGTextView Body Bold>
                {Boolean(App!.info["cas"]) && "为了确保用户行为的一致性和账户安全，逐梦园账号在 180 天内仅允许更改一次。"}
                {Boolean(!App!.info["cas"]) && "根据我们的规定，逐梦园账号在 180 天内仅允许更改一次。如需再次修改，请在 "}
                {Boolean(!App!.info["cas"]) && String(App!.info["cad"])}
                {Boolean(!App!.info["cas"]) && " 天后重试。感谢您的理解和配合。"}
            </DGTextView>

            {Boolean(App!.info["cas"]) && <Box>
                {/*账号输入框*/}
                <TextField
                    type="text" variant="standard" label="请输入新的账号：" autoComplete="username"
                    disabled={loading} defaultValue={account} onChange={handleChangeAccount}
                    error={AccountError.state} helperText={AccountError.text} fullWidth required/>
                {/*密码输入控制器 */}
                <FormControl
                    margin="dense" variant="standard" disabled={loading}
                    error={PasswordError.state} autoFocus fullWidth required>
                    {/* 密码提示语 */}
                    <InputLabel>请输入密码进行验证：</InputLabel>
                    {/* 密码输入框 */}
                    <Input
                        type={showPwd ? 'text' : 'password'} autoComplete="current-password"
                        value={password} onChange={handleChangePassword} endAdornment={<InputAdornment position="end">
                        {/* 显示、隐藏密码图标按钮 */}
                        <IconButton
                            disabled={loading} onClick={() => setShowPwd(!showPwd)}
                            onMouseDown={e => e.preventDefault()}>
                            {showPwd ? <VisibilityOff/> : <Visibility/>}
                        </IconButton>
                    </InputAdornment>}/>
                    {/* 密码错误信息 */}
                    <FormHelperText>{PasswordError.text}</FormHelperText>
                </FormControl>
            </Box>}
        </Box>}
    </>);
    const submitMethod = (App!.info && App!.info["cas"]) ? {
        name: "确定", click: () => handleSubmit()
    } : undefined;
    return (<Box>
        {/* Toast 组件 */}
        <DGToast state={toast} close={() => setToast({state: false, severity: toast.severity, text: toast.text})}/>
        {/* DGDialogLayout 样式 */}
        <DGDialogLayout
            load={loading} title="更改账号" state={state} close={() => handleClose(1)}
            submit={submitMethod} PANEL AUTO>
            {ContentView}
        </DGDialogLayout>
        {/* DGDrawerLayout 样式 */}
        <DGDrawerLayout
            load={loading} title="更改账号" state={state} close={() => handleClose(1)} flex="bottom"
            submit={submitMethod} PANEL AUTO>
            {ContentView}
        </DGDrawerLayout>
    </Box>);
}
export default ChangeAccount;